package com.haoshuang.zhouzhoubang.ui.page.order

import android.Manifest
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.alipay.face.api.ZIMFacade
import com.alipay.face.api.ZIMFacadeBuilder
import com.flyco.tablayout.SlidingTabLayout
import com.flyco.tablayout.listener.OnTabSelectListener
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.FragmentOrderBinding
import com.haoshuang.zhouzhoubang.model.bean.HomeDataBean
import com.haoshuang.zhouzhoubang.model.event.HomeJumpOrderIndexPageEvent
import com.haoshuang.zhouzhoubang.model.event.OrderStatusChangeEvent
import com.haoshuang.zhouzhoubang.model.event.RefreshHomeData
import com.haoshuang.zhouzhoubang.model.event.RefreshMasterOrderEvent
import com.haoshuang.zhouzhoubang.model.event.RefreshOrderNumEvent
import com.haoshuang.zhouzhoubang.model.event.RefreshTeamUserInfo
import com.haoshuang.zhouzhoubang.ui.activity.AgreementActivity
import com.haoshuang.zhouzhoubang.ui.adapter.ViewPagerAdapter
import com.haoshuang.zhouzhoubang.ui.dialog.BusinessLicenseDialog
import com.haoshuang.zhouzhoubang.ui.dialog.ChooseOrderStatusScreenDialog
import com.haoshuang.zhouzhoubang.ui.fragment.OrderListFragment
import com.haoshuang.zhouzhoubang.ui.fragment.OrderListStatusFragment
import com.haoshuang.zhouzhoubang.ui.page.order.receiveorder.ReceiveOrderListFragment
import com.haoshuang.zhouzhoubang.ui.page.order.scan.ScanActivity
import com.haoshuang.zhouzhoubang.ui.page.order.take.TakeOrderActivity
import com.haoshuang.zhouzhoubang.ui.page.settled.background.BackgroundInputInfoActivity
import com.haoshuang.zhouzhoubang.ui.page.settled.collaborationcosts.CollaborationCostsActivity
import com.haoshuang.zhouzhoubang.ui.page.settled.contactbutler.ContactButlerActivity
import com.haoshuang.zhouzhoubang.ui.page.settled.settled.StoreSettledInputActivity
import com.haoshuang.zhouzhoubang.ui.page.settled.upload.UploadBusinessLicenseActivity
import com.haoshuang.zhouzhoubang.utils.PermissionHelper
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lnkj.jialubao.utils.AccountUtils
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseVMFragment
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.LogUtil
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.gone
import com.mufeng.libs.utils.view.load
import com.mufeng.libs.utils.view.textColor
import com.mufeng.libs.utils.view.visible
import com.mufeng.libs.utils.view.visibleOrGone


/**
 *
 */
class OrderFragment : BaseVMFragment<OrderViewModel, FragmentOrderBinding>() {

    companion object {
        fun getInstance(): OrderFragment {
            val fragment = OrderFragment()
            fragment.arguments = Bundle().apply {

            }
            return fragment
        }
    }

    private val titles = arrayListOf("待抢单", "待服务", "进行中", "已完成", "返工单", "退款/售后")

    private val fragments = arrayListOf<Fragment>()

    // 0: 待抢单, 9: 待预约, 8: 待确认, 1: 待上门, 7: 已超时, 2: 服务中, 6: 待验收, 3: 已完成, 5: 返工单, 4: 退款/售后
    private var orderStatus = 0

    private var index = 0

    private var homeData: HomeDataBean? = null

    fun refreshData(){
        when(index){
            0 -> {
                // 刷新抢单列表
                (fragments[0] as ReceiveOrderListFragment).refreshData()
            }
            3 -> {
                // 刷新已完成列表
                (fragments[3] as OrderListStatusFragment).refreshData()
            }
            5 -> {
                // 刷新售后
                (fragments[5] as OrderListStatusFragment).refreshData()
            }
        }
    }

    override fun initView(savedInstanceState: Bundle?) {

        binding.tvTakeOrder.clickWithTrigger {
            if (homeData?.status != "8") {
                toast("请先入驻")
                return@clickWithTrigger
            }
            // 门店下单页面
            startPage<TakeOrderActivity>()
        }
        binding.ivScan.clickWithTrigger {
            if (homeData?.status != "8") {
                toast("请先入驻")
                return@clickWithTrigger
            }
            // 扫一扫
            PermissionHelper.requestPermission(
                mActivity,
                "权限使用说明",
                "用于扫一扫功能",
                Manifest.permission.CAMERA,
            ) {

                if (it) {
                    startPage<ScanActivity>()
                } else {
                    toast("请开启相机权限")
                }
            }


        }

        binding.ivScreen.clickWithTrigger {
            if (homeData?.status != "8") {
                toast("请先入驻")
                return@clickWithTrigger
            }
            // 获取当前选中的订单状态
            orderStatus = when (fragments[index]) {
                is OrderListFragment -> (fragments[index] as OrderListFragment).getOrderStatus()
                is OrderListStatusFragment -> (fragments[index] as OrderListStatusFragment).getOrderStatus()
                else -> 0
            }
            // 点击订单筛选
            XPopup.Builder(mActivity)
                .atView(binding.llTab)
                .asCustom(
                    ChooseOrderStatusScreenDialog(
                        context = mActivity,
                        status = orderStatus,
                        onChooseOrderStatus = {
                            orderStatus = it?:0
                            val status = when(orderStatus){
                                0 -> 0
                                9,8,1,7 -> 1
                                10,2,6 -> 2
                                3 -> 3
                                4 -> 4
                                5 -> 5
                                else -> 0
                            }
                            LiveEventBus.get(OrderStatusChangeEvent::class.java)
                                .post(OrderStatusChangeEvent(status, it))
                        },
                        onSearch = {

                        })
                )
                .show()
        }

        binding.tvRefresh.clickWithTrigger {
            vm.getHomeData()
        }

        initViewPager()

        // 联系管家
        binding.tvContactButler.click {
            startPage<ContactButlerActivity>()
        }

        // 门店入驻
        binding.tvConfirm.click {
            when (homeData?.status) {
                "-1" -> {
                    // 未入驻 去入驻
                    startPage<StoreSettledInputActivity>()
                }

                "0" -> {
                    // 待审核 联系管家
                    startPage<ContactButlerActivity>()
                }

                "2" -> {
                    // 审核未通过 重新认证
                    startPage<StoreSettledInputActivity>()
                }

                "3" -> {
                    // 未人脸 去认证
//                    startPage<FaceRecognitionActivity>()
                    PermissionHelper.requestPermission(
                        mActivity,
                        "权限使用说明",
                        "用于帮您实现实名认证, 人脸识别",
                        Manifest.permission.CAMERA,
                    ) {

                        if (it) {
                            val metaInfos = ZIMFacade.getMetaInfos(mActivity)
                            val name = AccountUtils.user?.user_name
                            val idNumber = AccountUtils.user?.id_card
                            vm.getFaceParams(name, idNumber, metaInfos)
                        } else {
                            toast("请开启相机权限")
                        }
                    }
                }

                "5" -> {
                    // 未签署合同 去签署
                    startPage<AgreementActivity>()
                }

                "7" -> {
                    // 未交费 立即支付
                    startPage<CollaborationCostsActivity>()
                }

                "9" -> {
                    // 后台录入 查看资料
                    startPage<BackgroundInputInfoActivity>()
                }
            }

        }

    }

    private fun initViewPager() {
        // 抢单
        fragments.add(ReceiveOrderListFragment.getInstance())
        // 待服务
        fragments.add(OrderListFragment.getInstance(1, 9))
        // 进行中
        fragments.add(OrderListFragment.getInstance(2, 10))
        // 已完成
        fragments.add(OrderListStatusFragment.getInstance(3))
        // 返工单
        fragments.add(OrderListFragment.getInstance(5, 1))
        // 退款/售后
        fragments.add(OrderListStatusFragment.getInstance(4))
        val adapter = ViewPagerAdapter(childFragmentManager, lifecycle, fragments)
        binding.viewPager.adapter = adapter
        binding.viewPager.isUserInputEnabled = false
        binding.viewPager.offscreenPageLimit = 6
        binding.viewPager.registerOnPageChangeCallback(object : OnPageChangeCallback(){
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                index = position
            }
        })
        binding.slidingTabLayout.setViewPager2(binding.viewPager, titles)

        binding.slidingTabLayout.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabClickListener(position: Int): Boolean {
                if (homeData?.status == "8"){
                    return true
                }else{
                    toast("请先入驻")
                    return false
                }
            }
            override fun onTabSelect(position: Int) {
                when(position){
                    0 -> {
                        // 刷新抢单列表
                        (fragments[0] as ReceiveOrderListFragment).refreshData()
                    }
                    3 -> {
                        // 刷新已完成列表
                        (fragments[3] as OrderListStatusFragment).refreshData()
                    }
                    5 -> {
                        // 刷新售后
                        (fragments[5] as OrderListStatusFragment).refreshData()
                    }
                }
            }

            override fun onTabReselect(position: Int) {
                when(position){
                    0 -> {
                        // 刷新抢单列表
                        (fragments[0] as ReceiveOrderListFragment).refreshData()
                    }
                    3 -> {
                        // 刷新已完成列表
                        (fragments[3] as OrderListStatusFragment).refreshData()
                    }
                    5 -> {
                        // 刷新售后
                        (fragments[5] as OrderListStatusFragment).refreshData()
                    }
                }
            }
        })

    }

    private fun setBadge(index: Int, count: Int) {
        if (count > 0) {
            val msgView = binding.slidingTabLayout.getMsgView(index)
            msgView.strokeWidth = 0
            msgView.backgroundColor = resources.getColor(R.color.c_3b76c2)
            msgView.textColor = R.color.white
            msgView.textSize = 10f

            binding.slidingTabLayout.showMsg(index, count)
            binding.slidingTabLayout.setMsgMargin(index, 2f, 10f)
        } else {
            binding.slidingTabLayout.hideMsg(index)
        }
    }

    override fun initData() {

    }

    override fun onResume() {
        super.onResume()
        vm.getHomeData()
        if (AccountUtils.user?.team?.team_end_time?.isNotEmpty() == true) {
            vm.getMasterOrderNum()
        }
    }

    override fun lazyLoadData() {

    }

    override fun startObserve() {

        // 刷新数据
        LiveEventBus.get(RefreshHomeData::class.java).observe(this) {
            isShowing = true
            vm.getHomeData()
        }

        LiveEventBus.get(HomeJumpOrderIndexPageEvent::class.java).observe(this) {
            binding.viewPager.setCurrentItem(it.index, false)
        }

        // 切换到服务中
        LiveEventBus.get("Sxx3", Boolean::class.java).observe(this) {
            LiveEventBus.get(OrderStatusChangeEvent::class.java).post(OrderStatusChangeEvent(2,2))
            LiveEventBus.get(RefreshMasterOrderEvent::class.java).post(RefreshMasterOrderEvent())
        }
        //预约后跳转到待上门列表
        LiveEventBus.get("Sxx6", Boolean::class.java).observe(this) {
            LiveEventBus.get(OrderStatusChangeEvent::class.java).post(OrderStatusChangeEvent(1,1))
            LiveEventBus.get(RefreshMasterOrderEvent::class.java).post(RefreshMasterOrderEvent())
        }
        //抢单成功 跳转到待确认
        LiveEventBus.get("Qdcg", Boolean::class.java).observe(this) {
            LiveEventBus.get(OrderStatusChangeEvent::class.java).post(OrderStatusChangeEvent(1,8))
            LiveEventBus.get(RefreshMasterOrderEvent::class.java).post(RefreshMasterOrderEvent())
        }
        //服务完成 跳转到待验收
        LiveEventBus.get("Sxx", Boolean::class.java).observe(this) {
            LiveEventBus.get(OrderStatusChangeEvent::class.java).post(OrderStatusChangeEvent(2,6))
            LiveEventBus.get(RefreshMasterOrderEvent::class.java).post(RefreshMasterOrderEvent())
        }

        //抢单成功 跳转到待上门
        LiveEventBus.get("Qdcg2", Boolean::class.java).observe(this) {
            LiveEventBus.get(OrderStatusChangeEvent::class.java).post(OrderStatusChangeEvent(1,1))
            LiveEventBus.get(RefreshMasterOrderEvent::class.java).post(RefreshMasterOrderEvent())
        }

        // 订单状态切换事件
        // 0: 待抢单, 9: 待预约, 8: 待确认, 1: 待上门, 7: 已超时, 2: 服务中, 6: 待验收, 3: 已完成, 5: 返工单, 4: 退款/售后 10 : 上门中
        LiveEventBus.get(OrderStatusChangeEvent::class.java).observeSticky(this) {
            when (it.orderStatus) {
                0 -> {
                    binding.viewPager.setCurrentItem(0, true)
                }
                9, 8, 1, 7 -> binding.viewPager.setCurrentItem(1, true)
                10, 2, 6 -> binding.viewPager.setCurrentItem(2, true)
                3 -> {
                    binding.viewPager.setCurrentItem(3, true)
                }

                5 -> binding.viewPager.setCurrentItem(4, true)
                4 -> binding.viewPager.setCurrentItem(5, true)
            }
        }

        LiveEventBus.get(RefreshOrderNumEvent::class.java).observe(this) {
            vm.getMasterOrderNum()
        }

        // 设置数量
        vm.getMasterOrderNumData.observeState(this) {
            onLoading { }
            onError { code, msg ->

            }
            onSuccess {
                // 刷新待服务的订单数量
                (fragments[1] as OrderListFragment).setOrderNum(it)
                (fragments[2] as OrderListFragment).setOrderNum(it)
                (fragments[4] as OrderListFragment).setOrderNum(it)
                setBadge(0, it?.take_task_count ?: 0)
                setBadge(1, it?.wait_service_count ?: 0)
                setBadge(2, it?.work_service_count ?: 0)
                setBadge(3, it?.finish_service_count ?: 0)
                setBadge(4, it?.rework_total ?: 0)
                setBadge(5, it?.after_sales_service_count ?: 0)
            }
        }

        vm.getHomeDataData.observeState(this) {
            onSuccess {
                homeData = it?.data
                setupData()
            }
        }

        vm.getFaceParamsData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                verify(it?.data?.certifyId ?: "")
            }
        }

        vm.faceRecognitionCallbackData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                startPage<AgreementActivity>()
                LiveEventBus.get(RefreshTeamUserInfo::class.java).post(RefreshTeamUserInfo)
                vm.getHomeData()
            }
        }

        vm.checkStoreLicenseData.observeState(this) {
            onError { code, msg ->
                // 未上传营业执照
                XPopup.Builder(mActivity)
                    .asCustom(BusinessLicenseDialog(mActivity) {
                        startPage<UploadBusinessLicenseActivity>()
                    })
                    .show()
            }
        }
    }

    /**
     * 开始人脸识别
     * @param certifyID String
     */
    private fun verify(certifyID: String) {
        val extParams = HashMap<String, String>()
        //如需指定活体检测UI界面方向(横屏+竖屏)，请指定这一项。
        extParams.put(
            ZIMFacade.ZIM_EXT_PARAMS_KEY_SCREEN_ORIENTATION,
            ZIMFacade.ZIM_EXT_PARAMS_VAL_SCREEN_PORT
        )
        //如需支持活体视频返回，请指定这一项，并在response.videoFilePath中获取视频本地路径。
        extParams[ZIMFacade.ZIM_EXT_PARAMS_KEY_USE_VIDEO] =
            ZIMFacade.ZIM_EXT_PARAMS_VAL_USE_VIDEO_TRUE
        //如需设置OCR的“下一步”按钮颜色（默认可不设置），请设置此项，如红色 #FF0000。
        extParams[ZIMFacade.ZIM_EXT_PARAMS_KEY_OCR_BOTTOM_BUTTON_COLOR] = "#FF0000"
        //如需自定义活体检测页面的进度条颜色（默认可不设置），请设置此项，如红色 #FF0000。
        extParams[ZIMFacade.ZIM_EXT_PARAMS_KEY_FACE_PROGRESS_COLOR] = "#FF0000"
        val zimFacade = ZIMFacadeBuilder.create(mActivity)
        zimFacade.verify(certifyID, true, extParams) { response ->
            if (1000 == response.code) {
                toast("认证成功")
                vm.faceRecognitionCallback()
            } else {
                toast("认证失败${response.code}")
                LogUtil.debugInfo("认证失败${response.code}")
            }
            true
        }
    }

    /**
     * 设置入驻状态
     */
    private fun setupData() {
        binding.rivHead.load(homeData?.avatar, placeholder = R.mipmap.logo, error = R.mipmap.logo)
         if (homeData?.status == "8"){
             // 已入驻
             binding.llUnSettleInView.gone()
             binding.llStoreState.gone()
         }else{
             // 未入驻
             binding.llUnSettleInView.visible()
             binding.llStoreState.visible()
             // 设置未入驻的信息显示
             when (homeData?.status) {
                 "-1" -> {
                     // 未入驻
                     binding.tvStoreState.text = "门店状态: 未入驻"
                     binding.tvStoreStateDescription.text = "当前门店状态未入驻, 请填写资料进行入驻"
                     // 显示联系管家
                     binding.tvContactButler.visibleOrGone(true)
                     // 显示门店入驻
                     binding.tvConfirm.visibleOrGone(true)
                     binding.tvConfirm.text = "去入驻"
                 }

                 "0" -> {
                     // 待审核
                     binding.tvStoreState.text = "门店状态: 待审核"
                     binding.tvStoreStateDescription.text = "当前门店状态待审核, 如有疑问请联系管家"
                     binding.tvContactButler.visibleOrGone(false)
                     binding.tvConfirm.visibleOrGone(true)
                     binding.tvConfirm.text = "联系管家"
                 }

                 "2" -> {
                     // 审核未通过
                     binding.tvStoreState.text = "门店状态: 已拒绝"
                     binding.tvStoreStateDescription.text = "当前门店状态被拒绝, ${homeData?.fail_msg}"
                     binding.tvContactButler.visibleOrGone(false)
                     binding.tvConfirm.visibleOrGone(true)
                     binding.tvConfirm.text = "重新认证"
                 }

                 "3" -> {
                     // 未人脸
                     binding.tvStoreState.text = "门店状态: 识别认证"
                     binding.tvStoreStateDescription.text = "当前门店状态为未实名, 请前往进行人脸识别"
                     binding.tvContactButler.visibleOrGone(false)
                     binding.tvConfirm.visibleOrGone(true)
                     binding.tvConfirm.text = "去认证"
                 }

                 "5" -> {
                     // 未签署合同
                     binding.tvStoreState.text = "门店状态: 签署合同"
                     binding.tvStoreStateDescription.text = "当前门店状态为未签合同, 请前往签署合同"
                     binding.tvContactButler.visibleOrGone(false)
                     binding.tvConfirm.visibleOrGone(true)
                     binding.tvConfirm.text = "去签署"
                 }

                 "7" -> {
                     // 未交费
                     binding.tvStoreState.text = "门店状态: 支付合作费用"
                     binding.tvStoreStateDescription.text =
                         "当前门店状态为未支付费用, 请前往进行支付费用"
                     binding.tvContactButler.visibleOrGone(false)
                     binding.tvConfirm.visibleOrGone(true)
                     binding.tvConfirm.text = "立即支付"
                 }

                 "9" -> {
                     // 后台录入
                     binding.tvStoreState.text = "门店状态: 确认资料"
                     binding.tvStoreStateDescription.text =
                         "管家已经完成资料录入, 请前往确认资料并提交审核"
                     binding.tvContactButler.visibleOrGone(false)
                     binding.tvConfirm.visibleOrGone(true)
                     binding.tvConfirm.text = "查看资料"
                 }
             }
         }

        // 获取门店是否上传营业执照
        if (homeData?.status == "8") {
            vm.checkStoreLicense()
        }
    }

}